<?php

namespace app\admin\controller;

use app\admin\model\FightDetail;
use app\admin\model\MemberEarningDetail;
use app\admin\model\OpenEggDetail;
use app\admin\model\SysConfig;
use app\admin\model\TransactionDetail;
use app\admin\service\GeetestLib;
use app\admin\service\PasswordHash;
use app\api\controller\Login;
use app\common\Cache\SystemConfigCache;
use think\Db;
use app\admin\model\Member;
use think\facade\Env;
use think\facade\Session;

class Index extends AdminBase
{

    private $id = "b46d1900d0a894591916ea94ea91bd2c";
    private $key = "36fc3fe98530eea08dfc6ce76e3d24c4";

    public function index()
    {
        include ROOT_PATH . "/application/admin/conf/menu.php";

        $this->assign("menu", $menu['admin']);
        return $this->fetch();
    }

    public function welcome()
    {
        $id = input('id');
        if (empty($id)) {
            $type = 1;
        } else {
            $type = (int)$id;
        }
        $start_time = strtotime(date("Y-m-d 00:00:00"));
        $end_time = strtotime(date("Y-m-d 23:59:59"));
        $total_user = Member::getInstance()->getCount();
        $new_user = Member::getInstance()->getCount("add_time between {$start_time} and {$end_time}");
        // 开蛋数
        $total_egg = OpenEggDetail::getInstance()->getCount();
        $today_egg = OpenEggDetail::getInstance()->getCount("add_time between {$start_time} and {$end_time}");
        $total_sliver_egg = OpenEggDetail::getInstance()->getCount("type = 0");
        $new_silver_egg = OpenEggDetail::getInstance()->getCount("type = 0 and add_time between {$start_time} and {$end_time}");
        $total_golden_egg = OpenEggDetail::getInstance()->getCount("type = 1");
        $new_golden_egg = OpenEggDetail::getInstance()->getCount("type = 1 and add_time between {$start_time} and {$end_time}");


        // 开蛋数(金蛋、银蛋)统计
        $day_time = input('day_time');
        $egg_type = intval(input('type', 2));
        if (empty($day_time)) {
            // 如果都不存在，则默认展示最近七天的开蛋数据
            $egg_start_time = date("Y-m-d 00:00:00", strtotime("-7 day"));
            $egg_ends_time = strtotime(date("Y-m-d", time())) + 86399;
            $egg_ends_time = date("Y-m-d H:i:s", $egg_ends_time);
            if ($egg_type == 2) {
                $total_egg_where = "add_time >= '{$egg_start_time}' and add_time <= '{$egg_ends_time}'";
            } else {
                $total_egg_where = "type = {$egg_type} and add_time >= '{$egg_start_time}' and add_time <= '{$egg_ends_time}'";
            }
        } else {
            $times = explode(" - ", $day_time);
            $egg_start_time = $times[0] . " 00:00:00";
            $egg_ends_time = $times[1] . " 23:59:59";
            if ($egg_type == 2) {
                $total_egg_where = "add_time >= '{$egg_start_time}' and add_time <= '{$egg_ends_time}'";
            } else {
                $total_egg_where = "type = {$egg_type} and add_time >= '{$egg_start_time}' and add_time <= '{$egg_ends_time}'";
            }
        }

        $sql = "SELECT count(user_address) as count, DAY (add_time) AS DAY, DATE_FORMAT (add_time,'%Y-%m-%d') AS time FROM dn_open_egg_detail WHERE ";
        $sql .= $total_egg_where;
        $sql .= " group by DAY";

        $result = Db::query($sql);
        $date_list = $num_list = [];
        foreach ($result as $key => $item) {
            $date_list[$key] = $item['DAY'];
            $num_list[$key] = $item['count'];
        }

        // 战斗次数
        $f_start_time = date("Y-m-d H:i:s", $start_time);
        $f_end_time = date("Y-m-d H:i:s", $end_time);
        $today_fight = FightDetail::getInstance()->getCount("add_time between '{$f_start_time}' and '{$f_end_time}'");
        $total_fight = FightDetail::getInstance()->getCount();
        // 金币效率
        $today_fight_fight = FightDetail::getInstance()->getSum("add_time between '{$f_start_time}' and '{$f_end_time}'", 'fight_gold');
        $today_drop_fight = FightDetail::getInstance()->getSum("add_time between '{$f_start_time}' and '{$f_end_time}'", 'drop_gold');
        $total_fight_fight = FightDetail::getInstance()->getSum([], 'fight_gold');
        $total_drop_fight = FightDetail::getInstance()->getSum([], 'drop_gold');
        if ($today_drop_fight == 0) {
            $today_rate = 0;
        } else {
            $today_rate = $today_fight_fight / $today_drop_fight;
        }
        if ($total_drop_fight == 0) {
            $total_rate = 0;
        } else {
            $total_rate = $total_fight_fight / $total_drop_fight;
        }

        // 部落出币量
        $today_coin = MemberEarningDetail::getInstance()->getSum("add_time between {$start_time} and {$end_time}", 'earning');
        $total_coin = MemberEarningDetail::getInstance()->getSum([], 'earning');

        // 交易明细（集市交易量、集市交易金额）
        $today_count = TransactionDetail::getInstance()->getCount("return_time between {$start_time} and {$end_time}");
        $total_count = TransactionDetail::getInstance()->getCount([]);
        $today_amount = TransactionDetail::getInstance()->getSum("return_time between {$start_time} and {$end_time}",
            'trans_price');
        $total_amount = TransactionDetail::getInstance()->getSum([], 'trans_price');


        // 战斗次数、金币效率统计
        $fight_day_time = input('fight_day_time');
        if (empty($fight_day_time)) {
            // 如果都不存在，则默认展示最近七天的开蛋数据
            $fight_start_time = date("Y-m-d 00:00:00", strtotime("-7 day"));
            $fight_ends_time = strtotime(date("Y-m-d", time())) + 86399;
            $fight_ends_time = date("Y-m-d H:i:s", $fight_ends_time);
            $total_fight_where = "add_time >= '{$fight_start_time}' and add_time <= '{$fight_ends_time}'";
        } else {
            $fight_times = explode(" - ", $fight_day_time);
            $fight_start_time = $fight_times[0] . " 00:00:00";
            $fight_ends_time = $fight_times[1] . " 23:59:59";
            $total_fight_where = "add_time >= '{$fight_start_time}' and add_time <= '{$fight_ends_time}'";
        }
        // 金币效率
        $rate_sql = "SELECT sum(gold_efficiency) as rate, DAY (add_time) AS DAY, DATE_FORMAT (add_time,'%Y-%m-%d') AS time FROM dn_fight_detail WHERE ";
        $rate_sql .= $total_fight_where;
        $rate_sql .= " group by DAY";
        $rate_result = Db::query($rate_sql);
        $rate_num_list = [];
        foreach ($rate_result as $key => $item) {
            $rate_num_list[$key] = $item['rate'];
        }
        // 战斗次数
        $fight_sql = "SELECT count(id) as count, DAY (add_time) AS DAY, DATE_FORMAT (add_time,'%Y-%m-%d') AS time FROM dn_fight_detail WHERE ";
        $fight_sql .= $total_fight_where;
        $fight_sql .= " group by DAY";
        $fight_result = Db::query($fight_sql);
        $fight_date_list = $fight_num_list = [];
        foreach ($fight_result as $key => $item) {
            $fight_date_list[$key] = $item['DAY'];
            $fight_num_list[$key] = $item['count'];
        }

        $data = [
            'today_count' => $today_count,
            'total_count' => $total_count,
            'today_amount' => $today_amount,
            'total_amount' => $total_amount,
            'total_user' => $total_user,
            'new_user' => $new_user,
            'total_egg' => $total_egg,
            'today_egg' => $today_egg,
            'total_sliver_egg' => $total_sliver_egg,
            'new_silver_egg' => $new_silver_egg,
            'total_golden_egg' => $total_golden_egg,
            'new_golden_egg' => $new_golden_egg,
            'type' => $type,
            'egg_type' => $egg_type,
            'today_fight' => $today_fight,
            'total_fight' => $total_fight,
            'today_rate' => keep($today_rate, 4),
            'total_rate' => keep($total_rate, 4),
            'today_coin' => $today_coin,
            'total_coin' => $total_coin,
            'date_list' => json_encode($date_list),
            'num_list' => json_encode($num_list),
            'fight_date_list' => json_encode($fight_date_list),
            'fight_num_list' => json_encode($fight_num_list),
            'rate_num_list' => json_encode($rate_num_list),
        ];
        $this->assign("data", $data);
        $this->assign("id", $type);
        return $this->fetch();
    }


    public function sendToSocket()
    {

        //利用API推送信息给socket服务器  推送的url地址，使用自己的服务器地址
        $push_api_url = "http://127.0.0.1:2121";  // 这个要与服务端的 new Worker('http://0.0.0.0:2121')做区分
        $post_data = array(
            "type" => "publish",
            "content" => "这个是推送给服务器的测试数据",
            "to" => '222',   // 给指定用户推送信息  to为组名
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $push_api_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Expect:"));
        $return = curl_exec($ch);
        curl_close($ch);
    }

    /**
     * geetest生成验证码
     */
    public function geetest_show_verify()
    {

        $gtLib = new GeetestLib($this->id, $this->key);
        //dump($gtLib);exit;
        $userId = "test";
        $digestmod = "md5";
        $params = [
            "digestmod" => $digestmod,
            "user_id" => $userId,
            "client_type" => "web",
            "ip_address" => "127.0.0.1"
        ];
        $result = $gtLib->register($digestmod, $params);
        // 将结果状态写到session中，此处register接口存入session，后续validate接口会取出使用
        // 注意，此demo应用的session是单机模式，格外注意分布式环境下session的应用
        Session::set(GeetestLib::GEETEST_SERVER_STATUS_SESSION_KEY, $result->getStatus());
        Session::set("userId", $userId);
        // 注意，不要更改返回的结构和值类型
        //dump($result->getData());exit;
        echo $result->getData();
    }

    public function login()
    {
        //查询后台密钥
        $admin_sign = SystemConfigCache::getConfig('ADMIN_SIGN');
        if (empty(input('sign')) || input('sign') != $admin_sign) {
            return false;
        }
        if (request()->isPost()) {
            $user_login = input('param.user_login');
            $user_pass = input('param.user_pass');

            $gtLib = new GeetestLib($this->id, $this->key);
            $challenge = input(GeetestLib::GEETEST_CHALLENGE);
            $validate = input(GeetestLib::GEETEST_VALIDATE);
            $seccode = input(GeetestLib::GEETEST_SECCODE);
            $status = Session::get(GeetestLib::GEETEST_SERVER_STATUS_SESSION_KEY);
            $userId = Session::get('userId');
            //验证极验证
            if ($status === null) {
                return json(['code' => 3, 'msg' => '验证码错误']);
            }
            $result = null;
            if ($status === 1) {
                $params = ["user_id" => $userId, "client_type" => "web", "ip_address" => "127.0.0.1"];
                $result = $gtLib->successValidate($challenge, $validate, $seccode, $params);
            } else {
                $result = $gtLib->failValidate($challenge, $validate, $seccode);
            }
            // 注意，不要更改返回的结构和值类型
            if ($result->getStatus() !== 1) {
                return json(['code' => 3, 'msg' => $result->getMsg()]);
            }

            $checkLogin = Db::name('user')->where('user_login', $user_login)->find();

            if (is_array($checkLogin) && count($checkLogin) > 0) {

                $hasher = new PasswordHash(8, true);

                $chekcPass = $hasher->CheckPassword($user_pass, $checkLogin['user_pass']);

                if (!$chekcPass) {

                    return json(['code' => 3, 'msg' => '密码不正确']);
                }

                $roleInfo = Db::name('role')->where('role_id', $checkLogin['user_role'])->find();
                session('is_login', true);
                session('user_id', $checkLogin['user_id']);
                session('user_login', $checkLogin['user_login']);
                session('user_status', $checkLogin['user_status']);
                session('user_role', $checkLogin['user_role']);
                session('role_name', $roleInfo['role_name']);

                $token = (new Login())->saveToCache($checkLogin['user_id'], $checkLogin['user_login'], 0, 2);
                return json(['code' => 1, 'msg' => '登入成功', 'jumpUrl' => "index"]);

            } else {

                return json(['code' => 2, 'msg' => '用户名不正确']);
            }
            exit();
        } else {
            $this->assign('data', $admin_sign);
            return $this->fetch();
        }
    }

    public function loginOut()
    {
        $id = session('user_id');
        // 删除失效Token，保证账号唯一登录
        $re_token = redis()->get($id);
        if ($re_token) {
            redis()->del($id);
            redis()->del($re_token);
        }
        session(null); // 清除session 安全退出帐号
        $this->redirect('admin/Index/login', 302);
    }


    public function vertify()
    {
        $config = [
            // 验证码字体大小
            'fontSize' => 80,
            // 验证码位数
            'length' => 4,
            // 关闭验证码杂点
            'useNoise' => true,
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }

}
